<?php

class AuthModule extends CWebModule
{
    public $userClassName = 'AdminUser';
    public $usernameFieldName = 'username';
    
    public $superUsername = 'Admin';
    public $entryPassword;
    public $afterEntryLoginedRedirect;
    
    public $alwaysAllows = array();
    public $alwaysAllowsAfterEntryLogined = array();
    
    /**
     * the superuser model record.
     * @var CModel
     */
    protected $_superUser;
    
    const ENTRY_LOGINED_KEY = 'entryLogined';
    
	public function init()
	{
		// import the module-level models and components
		$this->setImport(array(
			'auth.models.*',
			'auth.components.*',
		));
        
        $this->setComponents(array(
            'generator'=>array(
				'class'=>'AuthGenerator',
                'controllerPaths'=>array(
                    Yii::app()->getControllerPath(),
                    $this->getName()=>$this->getControllerPath(),
                ),
			),
        ));
        
        if( ! isset($this->entryPassword{5}))
            throw new CException('the entryPassword can\'t be empty and the entryPassword must be longer than 5 chars');
	}
    
    public function getSuperUser($autoCreate=false)
    {
        if(empty($this->_superUser))
            $this->_superUser = AdminUser::model()->findByAttributes(array($this->usernameFieldName=>$this->superUsername));
        
        if(empty($this->_superUser) && $autoCreate)
        {
            $adminUser = new $this->userClassName;
            $adminUser->{$this->usernameFieldName} = $this->superUsername;
            return $adminUser;
        }
        
        return $this->_superUser;
    }
    
    public function getSuperUsername()
    {
        return $this->superUsername;
    }
    
    public function getIsSuperUser()
    {
        if( ! Yii::app()->user->getIsGuest())
            return Yii::app()->user->name == $this->superUsername;
        else
            return false;
    }
    
    static public function setEntryLogined($value)
    {
        return Yii::app()->session->add(self::ENTRY_LOGINED_KEY, $value);
    }    
    
    static public function getEntryLogined()
    {
        return Yii::app()->session->get(self::ENTRY_LOGINED_KEY);
    }
    
    public function getHasInstalled()
    {
        $superUser = $this->getSuperUser();
        return ! empty($superUser);
    }
    
    public function createUrl($route, $params=array(), $ampersand='&')
	{
        if(0 !== strpos($route, '/'))
            $route = '/'.$this->getName().'/'.$route;
        
        return Yii::app()->createUrl($route, $params=array(), $ampersand='&');
	}
    
    public function getInstallUrl()
    {
        return $this->createUrl('install/index');
    }
}
